//
//  CWUserAccount.swift
//  CWWeibo06
//
//  Created by ycw on 2017/7/25.
//  Copyright © 2017年 xiaowei. All rights reserved.
//

import UIKit

fileprivate let savePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.plist")

class CWUserAccount: NSObject,NSCoding {
    
    /**
     授权令牌
     */
    var access_token: String?
    /**
     超时时长
     */
    var expires_in: Int = 0 {
        didSet{
            expires_date = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    
    //为后面方便使用，将过期秒数转换成过期时间
    var expires_date: Date?
    
    /**
     用户ID
     */
    var uid: Int64 = 0
    /**
     用户名
     */
    var name: String?
    /**
     用户头像
     */
    var avatar_large: String?
    
    init(dict: [String:Any]) {
        super.init()
        
        setValuesForKeys(dict)
        
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
        
    }
    
    //MARK: 属性归档和解档
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        expires_date = aDecoder.decodeObject(forKey: "expires_date") as! Date?
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as! String?
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
    }
    
    //向外界提供一个保存用户账户信息的方法
    open func saveUserAccount() {
        
        //进行归档
        NSKeyedArchiver.archiveRootObject(self, toFile: savePath)
        
    }
    
    //读取用户账户的方法
    class func readUserAccount() -> CWUserAccount? {
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: savePath) as? CWUserAccount
        
        return userAccount
    }
    

}
